package com.cb.web.wasf.sample.web;

import com.cb.web.wasf.Message.FreeMessage;
import com.cb.web.wasf.Request;
import com.cb.web.wasf.State;
import com.cb.web.wasf.View;
import com.cb.web.wasf.View.JspView;
import com.cb.web.wasf.sample.model.BONotFoundException;
import com.cb.web.wasf.sample.model.SubList;
import com.cb.web.wasf.sample.model.UserBO;

/**
 * @author CBO
 */
public class UserListState extends AbstractMenuSupportState {

    private int fromIndex;
    private int pageSize = 5;
    private SubList<UserBO> users;

    public UserListState() {
        super();
        loadUserListFromDatabase();
    }

    public final void loadUserListFromDatabase() {
        users = ManagerLocator.getUserManager().getSubList(fromIndex, pageSize);
    }

    public SubList<UserBO> getUsers() {
        return users;
    }

    public State prevPage(Request request) {
        clearMessages();
        fromIndex -= pageSize;
        loadUserListFromDatabase();
        return this;
    }

    public State nextPage(Request request) {
        clearMessages();
        fromIndex += pageSize;
        loadUserListFromDatabase();
        return this;
    }

    public State createUser(Request request) {
        clearMessages();
        return UserEditState.creation(this);
    }

    public State editUser(Request request) {
        clearMessages();
        try {
            return UserEditState.modification(this, Long.valueOf(request.getEventSource()));
        } catch (BONotFoundException bonfe) {
            addMessage(new FreeMessage("Edition impossible, l'utilisteur a été supprimé. La liste a été mise à jour."));
            loadUserListFromDatabase();
            return this;
        }
    }

    public State deleteUser(Request request) {
        clearMessages();
        try {
            ManagerLocator.getUserManager().delete(Long.valueOf(request.getEventSource()));
            addMessage(new FreeMessage("Utilisateur supprimé"));
        } catch (BONotFoundException ex) {
            addMessage(new FreeMessage("Suppresion impossible, l'utilisateur à été préalablement supprimé. La liste a été mise à jour."));
        }
        loadUserListFromDatabase();
        return this;
    }

    @Override
    public View getView() {
        return new JspView(this, "/WEB-INF/jsp/userList.jsp");
    }
}
